package com.example.nkj.feather_android;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothManager;
import android.bluetooth.le.AdvertiseCallback;
import android.bluetooth.le.AdvertiseData;
import android.bluetooth.le.AdvertiseSettings;
import android.bluetooth.le.BluetoothLeAdvertiser;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;


/**
 * Created by nkj on 18-11-5.
 */

public class ble_adv extends AppCompatActivity {

    private EditText dev_name;
    private TextView tv_ble_adv_data;
    private TextView tv_mot1_speed_data;
    private TextView tv_mot2_speed_data;
    private TextView tv_mot3_speed_data;
    private TextView tv_mot4_speed_data;
    private SeekBar sb_mot1_speed_data;
    private SeekBar sb_mot2_speed_data;
    private SeekBar sb_mot3_speed_data;
    private SeekBar sb_mot4_speed_data;
    private CheckBox cb_link;
    private CheckBox cb_currper_link;
    private CheckBox cb_rts;
    private int mot1_speed_value=0;
    private int mot2_speed_value=0;
    private int mot3_speed_value=0;
    private int mot4_speed_value=0;
    private int config = 0;

    private BluetoothAdapter bluetoothAdapter;
    BluetoothManager bluetoothManager;
    BluetoothLeAdvertiser bluetoothAdvertiser;

    private final static int REQUEST_ENABLE_BT = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        //设置标题栏
        if (getSupportActionBar() != null) {
            getSupportActionBar().setTitle(R.string.ble_adv_title_name);
        }
        setContentView(R.layout.ble_adv);

        dev_name = (EditText)findViewById(R.id.editText_devname);
        tv_ble_adv_data = (TextView) this.findViewById(R.id.textView_ble_adv_data);
        tv_mot1_speed_data = (TextView) this.findViewById(R.id.textView_mot1_speed_data);
        tv_mot2_speed_data = (TextView) this.findViewById(R.id.textView_mot2_speed_data);
        tv_mot3_speed_data = (TextView) this.findViewById(R.id.textView_mot3_speed_data);
        tv_mot4_speed_data = (TextView) this.findViewById(R.id.textView_mot4_speed_data);
        sb_mot1_speed_data = (SeekBar) findViewById(R.id.seekBar_mot1_speed_data);
        sb_mot2_speed_data = (SeekBar) findViewById(R.id.seekBar_mot2_speed_data);
        sb_mot3_speed_data = (SeekBar) findViewById(R.id.seekBar_mot3_speed_data);
        sb_mot4_speed_data = (SeekBar) findViewById(R.id.seekBar_mot4_speed_data);
        cb_link = (CheckBox) findViewById(R.id.checkBox_link);
        cb_currper_link = (CheckBox) findViewById(R.id.checkBox_currper_link);
        cb_rts = (CheckBox) findViewById(R.id.checkBox_rts);

        sb_mot1_speed_data.setMax(100);
        sb_mot2_speed_data.setMax(100);
        sb_mot3_speed_data.setMax(100);
        sb_mot4_speed_data.setMax(100);
        sb_mot1_speed_data.setOnSeekBarChangeListener(sbl);
        sb_mot2_speed_data.setOnSeekBarChangeListener(sbl);
        sb_mot3_speed_data.setOnSeekBarChangeListener(sbl);
        sb_mot4_speed_data.setOnSeekBarChangeListener(sbl);
        cb_link.setOnCheckedChangeListener(cbl);
        cb_currper_link.setOnCheckedChangeListener(cbl);
        cb_rts.setOnCheckedChangeListener(cbl);

        //判断手机是否支持BLE
        if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
            Toast.makeText(ble_adv.this,"Not Support BLE" , Toast.LENGTH_SHORT).show();
            startActivity(new Intent(ble_adv.this,MainActivity.class));
            finish();
        }

        bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
        bluetoothAdapter = bluetoothManager.getAdapter();
        bluetoothAdvertiser = bluetoothAdapter.getBluetoothLeAdvertiser();

        if((bluetoothAdapter != null && !bluetoothAdapter.isEnabled()) || bluetoothAdvertiser == null) {
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
            bluetoothAdvertiser = bluetoothAdapter.getBluetoothLeAdvertiser();
        }
        if(bluetoothAdvertiser == null)
        {
            Toast.makeText(ble_adv.this,"Not Support BLE Advertiser" , Toast.LENGTH_SHORT).show();
            startActivity(new Intent(ble_adv.this,MainActivity.class));
            finish();
        }

        dev_name.setText("Feather");
    }

    public void startAdvertising(byte[] data,int timeout)
    {
        if(bluetoothAdvertiser != null)
        {
            bluetoothAdvertiser.startAdvertising(createAdvSettings(false, timeout)
                    , createAdvertiseData(data), mAdvCallback);
        }
    }

    public void stopAdvertising()
    {
        bluetoothAdvertiser.stopAdvertising(mAdvCallback);
    }

    public AdvertiseSettings createAdvSettings(boolean connectable, int timeoutMillis)
    {
        AdvertiseSettings.Builder builder = new AdvertiseSettings.Builder();
        //设置广播的模式, 功耗相关
        builder.setAdvertiseMode(AdvertiseSettings.ADVERTISE_MODE_BALANCED);
        builder.setConnectable(connectable);
        builder.setTimeout(timeoutMillis);
        builder.setTxPowerLevel(AdvertiseSettings.ADVERTISE_TX_POWER_HIGH);
        AdvertiseSettings mAdvertiseSettings = builder.build();
        if (mAdvertiseSettings == null)
        {
            Log.e("BLE ADV", "mAdvertiseSettings == null");
        }
        return mAdvertiseSettings;
    }

    /**
     * create AdvertiseDate
     */
    public static AdvertiseData createAdvertiseData(byte[] data)
    {
        AdvertiseData.Builder mDataBuilder = new AdvertiseData.Builder();
        //mDataBuilder.setIncludeDeviceName(true);
        mDataBuilder.addManufacturerData(0xE502, data);
        AdvertiseData mAdvertiseData = mDataBuilder.build();
        return mAdvertiseData;
    }

    //设置扫描回复数据
//    public static AdvertiseData createScanResponseData(short major, short minor, byte txPower)
//    {
//        AdvertiseData.Builder builder = new AdvertiseData.Builder();
//        builder.setIncludeDeviceName(true);
//
//        byte[] serverData = new byte[5];
//        ByteBuffer bb = ByteBuffer.wrap(serverData);
//        bb.order(ByteOrder.BIG_ENDIAN);
//        bb.putShort(major);
//        bb.putShort(minor);
//        bb.put(txPower);
//        //builder.addServiceData(ParcelUuid.fromString(BluetoothUUID.bleServerUUID.toString()), serverData);
//
//        AdvertiseData adv = builder.build();
//        return adv;
//    }

    private AdvertiseCallback mAdvCallback = new AdvertiseCallback() {
        @Override
        public void onStartSuccess(AdvertiseSettings settingsInEffect) {
            super.onStartSuccess(settingsInEffect);

        }

        @Override
        public void onStartFailure(int errorCode) {
            super.onStartFailure(errorCode);

        }
    };

    public String get_set_mot_data()
    {
        final String data = dev_name.getText() + "-M" +
                String.format("%03d%03d%03d%03d",mot1_speed_value,mot2_speed_value,mot3_speed_value,mot4_speed_value);
        tv_ble_adv_data.setText(data+"\r\n\r\n"+String.format("%02X",data.length()+3)+"FF02E5"+byteToHex(data.getBytes()));
        return data;
    }
    /*
     * onProgressChanged：进度条改变事件
     * onStartTrackingTouch：进度条开始拖动事件
     * onStopTrackingTouch：进度条停止拖动事件
     * @see android.widget.SeekBar.OnSeekBarChangeListener
     */
    private SeekBar.OnSeekBarChangeListener sbl = new SeekBar.OnSeekBarChangeListener()
    {
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser)
        {
            if(seekBar.getId() == R.id.seekBar_mot1_speed_data)
            {
                mot1_speed_value = progress;
                tv_mot1_speed_data.setText(String.valueOf(mot1_speed_value)+"%");
            }
            else if (seekBar.getId() == R.id.seekBar_mot2_speed_data)
            {
                mot2_speed_value = progress;
                tv_mot2_speed_data.setText(String.valueOf(mot2_speed_value)+"%");
            }
            else if (seekBar.getId() == R.id.seekBar_mot3_speed_data)
            {
                mot3_speed_value = progress;
                tv_mot3_speed_data.setText(String.valueOf(mot3_speed_value)+"%");
            }
            else if (seekBar.getId() == R.id.seekBar_mot4_speed_data)
            {
                mot4_speed_value = progress;
                tv_mot4_speed_data.setText(String.valueOf(mot4_speed_value)+"%");
            }
            if((config & 0x01) == 0x01)//联动
            {
            }
            else if((config & 0x02) == 0x01)//百分比联动
            {
            }
            if((config & 0x04) == 0x04)//实时发送
            {
                startAdvertising(get_set_mot_data().getBytes(),300);
            }
        }
        public void onStartTrackingTouch(SeekBar seekBar)
        {
        }
        public void onStopTrackingTouch(SeekBar seekBar)
        {
        }
    };

    private CheckBox.OnCheckedChangeListener cbl = new CompoundButton.OnCheckedChangeListener()
    {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
        {
            //如果第一个 CheckBox 被选中
            if(buttonView.getId() == R.id.checkBox_link)
            {
                if (isChecked == true)
                {
                    config |= 0x01;
                    cb_currper_link.setChecked(false);
                }
                else
                {
                    config &= ~0x01;
                }
            }
            else if(buttonView.getId() == R.id.checkBox_currper_link)
            {
                if (isChecked == true)
                {
                    config |= 0x02;
                    cb_link.setChecked(false);
                }
                else
                {
                    config &= ~0x02;
                }
            }
            else if(buttonView.getId() == R.id.checkBox_rts)
            {
                if (isChecked == true)
                {
                    config |= 0x04;
                }
                else
                {
                    config &= ~0x04;
                }
            }
            //tv_ble_adv_data.setText(String.valueOf(config));
        }
    };

    public void onAdvButtonClick(View view)
    {
        switch(view.getId())
        {
            case R.id.button_ble_adv_back:
                stopAdvertising();
                startActivity(new Intent(ble_adv.this,MainActivity.class));
                finish();
                break;
            case R.id.button_off:
                mot1_speed_value = mot2_speed_value = mot3_speed_value = mot4_speed_value = 0;
                tv_mot1_speed_data.setText(String.valueOf(mot1_speed_value)+"%");
                tv_mot2_speed_data.setText(String.valueOf(mot2_speed_value)+"%");
                tv_mot3_speed_data.setText(String.valueOf(mot3_speed_value)+"%");
                tv_mot4_speed_data.setText(String.valueOf(mot4_speed_value)+"%");
                sb_mot1_speed_data.setProgress(mot1_speed_value);
                sb_mot2_speed_data.setProgress(mot2_speed_value);
                sb_mot3_speed_data.setProgress(mot3_speed_value);
                sb_mot4_speed_data.setProgress(mot4_speed_value);
                startAdvertising(get_set_mot_data().getBytes(),500);
                break;
            case R.id.button_hand_send:
                startAdvertising(get_set_mot_data().getBytes(),500);
                break;
        }
    }

    public boolean onKeyDown(int keyCode, KeyEvent event)
    {
        switch (keyCode)
        {
            case KeyEvent.KEYCODE_MENU:

                break;
            case KeyEvent.KEYCODE_BACK:
                stopAdvertising();
                startActivity(new Intent(ble_adv.this,MainActivity.class));
                finish();
                break;
            default:
                break;
        }
        return super.onKeyDown(keyCode, event);
    }

    public static String byteToHex(byte[] bytes)
    {
        String strHex = "";
        StringBuilder sb = new StringBuilder("");
        for (int n = 0; n < bytes.length; n++) {
            strHex = Integer.toHexString(bytes[n] & 0xFF);
            sb.append((strHex.length() == 1) ? "0" + strHex : strHex); // 每个字节由两个字符表示，位数不够，高位补0
        }
        return sb.toString().trim().toUpperCase();
    }
}
